// reports.ts
Page({
  data: {
    selectedPeriod: 'week', // week, month, year
    reportData: {
      totalSales: 0,
      totalVolume: 0,
      orderCount: 0,
      avgOrderValue: 0
    },
    chartData: [],
    fuelTypeData: [],
    dateRange: ''
  },

  onLoad() {
    this.loadReportData()
  },

  switchPeriod(e: any) {
    const period = e.currentTarget.dataset.period
    this.setData({
      selectedPeriod: period
    })
    this.loadReportData()
  },

  loadReportData() {
    const { selectedPeriod } = this.data
    const records = wx.getStorageSync('fuelRecords') || []
    
    // 根据选择的时间段过滤数据
    const filteredRecords = this.filterRecordsByPeriod(records, selectedPeriod)
    
    // 计算统计数据
    const reportData = this.calculateReportData(filteredRecords)
    
    // 生成图表数据
    const chartData = this.generateChartData(filteredRecords, selectedPeriod)
    
    // 按油品类型统计
    const fuelTypeData = this.calculateFuelTypeData(filteredRecords)
    
    // 设置日期范围
    const dateRange = this.getDateRange(selectedPeriod)

    this.setData({
      reportData,
      chartData,
      fuelTypeData,
      dateRange
    })
  },

  filterRecordsByPeriod(records: any[], period: string) {
    const now = new Date()
    let startDate: Date

    switch (period) {
      case 'week':
        startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
        break
      case 'month':
        startDate = new Date(now.getFullYear(), now.getMonth(), 1)
        break
      case 'year':
        startDate = new Date(now.getFullYear(), 0, 1)
        break
      default:
        startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
    }

    return records.filter((record: any) => {
      const recordDate = new Date(record.date)
      return recordDate >= startDate && recordDate <= now
    })
  },

  calculateReportData(records: any[]) {
    let totalSales = 0
    let totalVolume = 0
    const orderCount = records.length

    records.forEach((record: any) => {
      totalSales += record.amount
      totalVolume += record.volume
    })

    const avgOrderValue = orderCount > 0 ? totalSales / orderCount : 0

    return {
      totalSales: totalSales.toFixed(2),
      totalVolume: totalVolume.toFixed(2),
      orderCount,
      avgOrderValue: avgOrderValue.toFixed(2)
    }
  },

  generateChartData(records: any[], period: string) {
    const dataMap = new Map()
    
    records.forEach((record: any) => {
      const date = new Date(record.date)
      let key: string

      switch (period) {
        case 'week':
          key = `${date.getMonth() + 1}/${date.getDate()}`
          break
        case 'month':
          key = `${date.getDate()}日`
          break
        case 'year':
          key = `${date.getMonth() + 1}月`
          break
        default:
          key = `${date.getMonth() + 1}/${date.getDate()}`
      }

      if (!dataMap.has(key)) {
        dataMap.set(key, { sales: 0, volume: 0, orders: 0 })
      }

      const data = dataMap.get(key)
      data.sales += record.amount
      data.volume += record.volume
      data.orders += 1
    })

    return Array.from(dataMap.entries()).map(([date, data]) => ({
      date,
      sales: data.sales.toFixed(2),
      volume: data.volume.toFixed(2),
      orders: data.orders
    }))
  },

  calculateFuelTypeData(records: any[]) {
    const typeMap = new Map()

    records.forEach((record: any) => {
      const type = record.fuelType
      if (!typeMap.has(type)) {
        typeMap.set(type, { sales: 0, volume: 0, orders: 0 })
      }

      const data = typeMap.get(type)
      data.sales += record.amount
      data.volume += record.volume
      data.orders += 1
    })

    return Array.from(typeMap.entries()).map(([type, data]) => ({
      type,
      sales: data.sales.toFixed(2),
      volume: data.volume.toFixed(2),
      orders: data.orders,
      percentage: 0 // 将在模板中计算
    }))
  },

  getDateRange(period: string) {
    const now = new Date()
    let startDate: Date

    switch (period) {
      case 'week':
        startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
        return `${this.formatDate(startDate)} - ${this.formatDate(now)}`
      case 'month':
        startDate = new Date(now.getFullYear(), now.getMonth(), 1)
        return `${now.getFullYear()}年${now.getMonth() + 1}月`
      case 'year':
        return `${now.getFullYear()}年`
      default:
        startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
        return `${this.formatDate(startDate)} - ${this.formatDate(now)}`
    }
  },

  formatDate(date: Date) {
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${month}/${day}`
  },

  exportReport() {
    wx.showModal({
      title: '导出报表',
      content: '报表导出功能开发中，敬请期待',
      showCancel: false
    })
  },

  refreshData() {
    wx.showLoading({
      title: '刷新中...'
    })
    
    setTimeout(() => {
      this.loadReportData()
      wx.hideLoading()
      wx.showToast({
        title: '数据已刷新',
        icon: 'success'
      })
    }, 1000)
  }
})